<template>
  <div>
    <app-head :nickname-value="userInfo.nickname" :avatarValue="userInfo.avatar"></app-head>
    <app-body>
      <div v-show="!eidtAddress">
        <div class="user-info-container">
          <div class="user-info-details">

            <el-upload action="http://localhost:9321/file/" :on-success="fileHandleSuccess"
                       :file-list="imgFileList" accept="image/*">
              <el-image style="width: 120px; height: 120px;border-radius: 10px;"
                        :src="$store.state.baseApi + userInfo.avatar" fit="contain"></el-image>
            </el-upload>
            <div class="user-info-details-text">
              <div class="user-info-details-text-nickname">{{ userInfo.nickname }}</div>
              <div class="user-info-details-text-time">{{ userInfo.signInTime }} 加入平台</div>
              <div class="user-info-details-text-edit">
                <el-button type="primary" plain @click="userInfoDialogVisible = true"> 编辑个人信息</el-button>
                <el-button type="success" plain @click="eidtAddress = true"> 编辑收货地址</el-button>
              </div>

              <el-dialog @close="finishEdit" title="编辑个人信息" :visible.sync="userInfoDialogVisible"
                         width="400px">
                <div class="edit-tip"> 昵称</div>
                <el-input v-model="userInfo.nickname" :disabled="notUserNicknameEdit"
                          @change="saveUserNickname">
                  <el-button slot="append" type="warning" icon="el-icon-edit"
                             @click="notUserNicknameEdit = false"> 修改昵称
                  </el-button>
                </el-input>
                <div class="edit-tip"> 手机号</div>
                <el-input v-model="userInfo.accountNumber" :disabled="notUserAccountNumberEdit"
                          @change="saveUserAccountNumber">
                  <el-button slot="append" type="warning" icon="el-icon-edit"
                             @click="notUserAccountNumberEdit = false"> 修改手机号
                  </el-button>
                </el-input>
                <div v-if="userPasswordEdit">
                  <div class="edit-tip">原密码</div>
                  <el-input v-model="userPassword1" show-password></el-input>
                  <div class="edit-tip">新密码</div>
                  <el-input v-model="userPassword2" show-password></el-input>
                  <div class="edit-tip">确认新密码</div>
                  <el-input v-model="userPassword3" show-password></el-input>
                  <div class="edit-tip"></div>
                  <el-button @click="savePassword" type="primary" plain> 确认修改密码</el-button>
                </div>
                <div v-else>
                  <div class="edit-tip">密码</div>
                  <el-input value="123456" :disabled="true" show-password>
                    <el-button slot="append" type="warning" icon="el-icon-edit"
                               @click="userPasswordEdit = true"> 修改密码
                    </el-button>
                  </el-input>
                </div>
                <span slot="footer" class="dialog-footer">
                                    <el-button @click="userInfoDialogVisible = false" type="primary"> 确认</el-button>
                                </span>
              </el-dialog>
            </div>
          </div>
        </div>
        <div class="tea-container">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="我的收藏" name="3"></el-tab-pane>
            <el-tab-pane label="我的文章收藏" name="4"></el-tab-pane>
            <el-tab-pane label="我喜欢的视频" name="7"></el-tab-pane>
<!--            <el-tab-pane label="购物车" name="4"></el-tab-pane>-->
            <el-tab-pane label="我买到的" name="5"></el-tab-pane>
          </el-tabs>
          <div class="tea-container-list">
            <div v-for="(item, index) in dataList[activeName - 1]" :key="index" class="tea-container-list-item">

              <div v-if="activeName === '7'" class="tea-container-list-item-detile" @click="toDetails(activeName, item)">
                <video height="100%" :src="'http://localhost:9321/'+item.scienceUrl" controls></video>
                <div class="tea-container-list-title">
                  {{ item.scienceName }}
                </div>
              </div>

              <div v-if="activeName === '4'" class="tea-container-list-item-detile">
                <div class="tea-container-list-title">
                  {{ item.topic.topicName }}
                  <p v-html="item.discuss.discussContent" class="tea-container-list-tea-details" style="height: 60px;overflow: hidden;font-size: 10px" ></p>
                </div>
              </div>

              <div v-if="activeName !== '7'&& activeName !== '4'" class="tea-container-list-item-detile" @click="toDetails(activeName, item)">
                <el-image style="width: 115px; height: 115px;" :src="$store.state.baseApi + item.imgUrl"
                          fit="cover">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline">无图</i>
                  </div>
                </el-image>
                <div class="tea-container-list-item-text">
                  <div class="tea-container-list-title">
                    {{ item.teaName }}
                  </div>
                  <div class="tea-container-list-tea-details">
                    {{ item.teaDetails }}
                  </div>
                  <div class="tea-container-list-tea-time">{{ item.timeStr }}</div>

                  <div class="tea-item-foot">
                    <div class="tea-prive">￥{{ item.teaPrice }}
                      {{ (activeName === '5') ? orderStatus[item.orderStatus] : '' }}
                    </div>
                    <el-button v-if="activeName !== '4' && activeName !== '5'" type="danger"
                               slot="reference" plain
                               @click.stop="handle(activeName, item, index)">{{ handleName[activeName - 1] }}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-show="eidtAddress" class="address-container">
        <el-page-header class="address-container-back" @back="eidtAddress = false" content="收货地址"></el-page-header>
        <div class="address-container-add">
          <div class="address-container-add-title"><b> 新增收货地址：</b></div>

          <div class="address-container-add-item">
            <el-input placeholder="请输入收货人姓名" v-model="addressInfo.consigneeName" maxlength="10" show-word-limit>
              <div slot="prepend">收货人姓名</div>
            </el-input>
          </div>
          <div class="address-container-add-item">
            <el-input placeholder="请输入收货人手机号" v-model="addressInfo.consigneePhone"
                      onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" maxlength="11" show-word-limit>
              <div slot="prepend">手机号</div>
            </el-input>
          </div>

          <div class="address-container-add-item">
            <span class="demonstration">省/市/区</span>
            <el-cascader :options="options" v-model="selectedOptions" @change="handleAddressChange"
                         :separator="' '">
            </el-cascader>
          </div>
          <div class="address-container-add-item">
            <el-input placeholder="请输入详细地址（如道路、门牌号、小区、楼栋号等信息）" v-model="addressInfo.detailAddress"
                      maxlength="50" show-word-limit>
              <div slot="prepend">详细地址</div>
            </el-input>
          </div>
          <el-checkbox v-model="addressInfo.defaultFlag">设置为默认地址</el-checkbox>
          <el-button type="success" style="margin-left: 20px;" @click="saveAddress"> 保存</el-button>
        </div>
        <div class="address-container-list">
          <hr>
          <div style="color: black;padding-left: 10px;font-size: 26px;"><b>已存在的收货地址：</b></div>
          <br>
          <el-table stripe :data="addressData" style="width: 100%">
            <el-table-column prop="consigneeName" label="收货人姓名" width="100">
            </el-table-column>
            <el-table-column prop="consigneePhone" label="手机号" width="120">
            </el-table-column>
            <el-table-column prop="detailAddressText" label="地址" width="270">
            </el-table-column>
            <el-table-column label="是否默认地址" width="110">
              <template slot-scope="scope">
                <el-button v-if="!scope.row.defaultFlag" size="mini"
                           @click="handleSetDefault(scope.$index, scope.row)">设为默认
                </el-button>
                <div v-else style="padding-left: 10px;color: #409EFF;">{{ scope.row.defaultAddress }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)"> 编辑
                </el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)"> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </app-body>
    <app-foot></app-foot>
  </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue';
import AppBody from '../common/AppPageBody.vue'
import AppFoot from '../common/AppFoot.vue'
import options from '../common/country-data.js'

export default {
  name: "me",
  components: {
    AppHead,
    AppBody,
    AppFoot
  },
  data() {
    return {
      imgFileList: [],
      addressInfo: {
        consigneeName: '',
        consigneePhone: '',
        provinceName: '',
        cityName: '',
        regionName: '',
        detailAddress: '',
        defaultFlag: false
      },
      activeName: '1',
      handleName: [' 下架', ' 删除', ' 取消收藏', '', ''],
      dataList: [
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
      ],
      orderStatus: ['待付款', '待发货', '待收货', '已完成', '已取消'],
      userInfoDialogVisible: false,
      notUserNicknameEdit: true,
      notUserAccountNumberEdit: true,
      userPasswordEdit: false,
      userPassword1: '',
      userPassword2: '',
      userPassword3: '',
      eidtAddress: false,
      selectedOptions: [],//存放默认值
      options: options,   //存放城市数据,
      userInfo: {
        accountNumber: "",
        avatar: "",
        nickname: "",
        signInTime: "",
      },
      addressData: []
    };
  },
  created() {
    if (!this.$globalData.userInfo.nickname) {
      this.$api.getUserInfo().then(res => {
        if (res.status_code === 1) {
          res.data.signInTime = res.data.signInTime.substring(0, 10);
          console.log(res.data);
          this.$globalData.userInfo = res.data;
          this.userInfo = this.$globalData.userInfo;
        }
      })
    } else {
      this.userInfo = this.$globalData.userInfo;
      console.log(this.userInfo);
    }
    this.getAddressData();
    this.getTeaItemData();
    this.getMyOrder();
    this.getMySoldtea();
    this.getMyFavorite();
    this.getMyLike();
    this.getMyCollect()
    this.handleClick()
  },
  methods: {
    getMyFavorite() {
      this.$api.getMyFavorite().then(res => {
        console.log('getMyFavorite', res);
        if (res.status_code === 1) {
          for (let i = 0; i < res.data.length; i++) {
            let pictureList = JSON.parse(res.data[i].teaItem.pictureList);
            this.dataList[2].push({
              favoriteId: res.data[i].id,
              id: res.data[i].teaItem.id,
              imgUrl: pictureList.length > 0 ? pictureList[0] : '',
              teaName: res.data[i].teaItem.teaName,
              teaDetails: res.data[i].teaItem.teaDetails,
              timeStr: res.data[i].createTime.substring(0, 10) + " " + res.data[i].createTime.substring(11, 19),
              teaPrice: res.data[i].teaItem.teaPrice
            });
          }
        }
      })
    },
    getMyLike() {
      this.$api.getMyLike().then(res => {
        console.log('getMyLike', res);
        if (res.status_code === 1) {
          for (let i = 0; i < res.data.length; i++) {
            this.dataList[6].push({
              createTime: res.data[i].createTime,
              scienceId: res.data[i].teaId,
              userId: res.data[i].userId,
              scienceName: res.data[i].teaScienceModel.scienceName,
              scienceUrl: res.data[i].teaScienceModel.scienceUrl,
              timeStr: res.data[i].createTime.substring(0, 10) + " " + res.data[i].createTime.substring(11, 19),
            });
          }
        }
      })
    },
    getMyCollect(){
      this.$api.myCollect().then(res => {
        console.log('getMyCollect', res);
        let collect = res.data;
        if (res.status_code === 1) {
          for (let i = 0; i < collect.length; i++) {
            this.$api.getDiscussByDiscussId({discussId: res.data[i].discussId}).then(res => {
              collect[i].discuss=res.data[0];
              this.$api.getTopic({id:res.data[0].topicId}).then(res => {
                collect[i].topic=res.data;
              })
            })
            this.dataList[3].push(collect[i]);
          }
        }
        console.log(this.dataList[3])
      })
    },
    getMySoldtea() {
      this.$api.getMySoldtea().then(res => {
        if (res.status_code === 1) {
          console.log('getMySoldtea', res.data);
          for (let i = 0; i < res.data.length; i++) {
            let pictureList = JSON.parse(res.data[i].teaItem.pictureList);
            this.dataList[3].push({
              id: res.data[i].id,
              imgUrl: pictureList.length > 0 ? pictureList[0] : '',
              teaName: res.data[i].teaItem.teaName,
              teaDetails: res.data[i].teaItem.teaDetails,
              timeStr: res.data[i].createTime.substring(0, 10) + " " + res.data[i].createTime.substring(11, 19),
              teaPrice: res.data[i].orderPrice,
              orderStatus: res.data[i].orderStatus
            });
          }
        }
      })
    },
    getMyOrder() {
      this.$api.getMyOrder().then(res => {
        if (res.status_code === 1) {
          console.log('getMyOrder', res.data);
          for (let i = 0; i < res.data.length; i++) {
            let pictureList = JSON.parse(res.data[i].teaItem.pictureList);
            this.dataList[4].push({
              id: res.data[i].id,
              imgUrl: pictureList.length > 0 ? pictureList[0] : '',
              teaName: res.data[i].teaItem.teaName,
              teaDetails: res.data[i].teaItem.teaDetails,
              timeStr: res.data[i].createTime.substring(0, 10) + " " + res.data[i].createTime.substring(11, 19),
              teaPrice: res.data[i].orderPrice,
              orderStatus: res.data[i].orderStatus
            });
          }
        }
      })
    },
    getTeaItemData() {
      this.$api.getAllteaItem().then(res => {
        console.log(res);
        if (res.status_code === 1) {
          for (let i = 0; i < res.data.length; i++) {
            res.data[i].timeStr = res.data[i].releaseTime.substring(0, 10) + " " + res.data[i].releaseTime.substring(11, 19);
            let pictureList = JSON.parse(res.data[i].pictureList);
            res.data[i].imgUrl = pictureList.length > 0 ? pictureList[0] : '';
            if (res.data[i].teaStatus === 1) {
              this.dataList[0].push(res.data[i]);
            } else if (res.data[i].teaStatus === 2) {
              this.dataList[1].push(res.data[i]);
            }
          }
        }
      })
    },
    getAddressData() {
      this.$api.getAddress().then(res => {
        if (res.status_code === 1) {
          let data = res.data;
          for (let i = 0; i < data.length; i++) {
            data[i].detailAddressText = data[i].provinceName + data[i].cityName + data[i].regionName + data[i].detailAddress;
            data[i].defaultAddress = data[i].defaultFlag ? '默认地址' : '设为默认';
          }
          console.log(data);
          this.addressData = data;
        }
      })
    },
    handleClick(tab, event) {
      console.log(this.activeName);
    },
    saveUserNickname() {
      this.notUserNicknameEdit = true;
      this.$api.updateUserPublicInfo({
        nickname: this.userInfo.nickname
      }).then(res => {
        console.log(res);
        this.$globalData.userInfo.nickname = this.userInfo.nickname;
      })

    },
    saveUserAccountNumber() {
      this.notUserAccountNumberEdit = true;
      this.$api.updateUserPublicInfo({
        accountNumber: this.userInfo.accountNumber
      }).then(res => {
        console.log(res);
        this.$globalData.userInfo.accountNumber = this.userInfo.accountNumber;
      })

    },
    savePassword() {
      if (!this.userPassword1 || !this.userPassword2) {
        this.$message.error('密码为空！');
      } else if (this.userPassword2 === this.userPassword3) {
        this.$api.updatePassword({
          oldPassword: this.userPassword1,
          newPassword: this.userPassword2
        }).then(res => {
          if (res.status_code === 1) {
            this.userPasswordEdit = false;
            this.$message({
              message: '修改成功！',
              type: 'success'
            });
            this.userPassword1 = '';
            this.userPassword2 = '';
            this.userPassword3 = '';
          } else {
            this.$message.error('旧密码错误，修改失败！');
          }
        })
      } else {
        this.$message.error('两次输入的密码不一致！');
      }

    },
    finishEdit() {
      this.notUserNicknameEdit = true;
      this.userInfoDialogVisible = false;
      this.userPasswordEdit = false;
    },
    handleAddressChange(value) {
      console.log(value);
      this.addressInfo.provinceName = value[0];
      this.addressInfo.cityName = value[1];
      this.addressInfo.regionName = value[2];
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.addressInfo = JSON.parse(JSON.stringify(row));
      this.selectedOptions = ['', '', ''];
      this.selectedOptions[0] = row.provinceName;
      this.selectedOptions[1] = row.cityName;
      this.selectedOptions[2] = row.regionName;
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm('是否确定删除该地址?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deleteAddress(row).then(res => {
          if (res.status_code === 1) {
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
            this.addressData.splice(index, 1);
            if (row.defaultFlag && this.addressData.length > 0) {
              this.addressData[0].defaultFlag = true;
              this.addressData[0].defaultAddress = '默认地址';
              this.update({
                id: this.addressData[0].id,
                defaultFlag: true
              });
            }
          } else {
            this.$message.error('系统异常，删除失败！')
          }
        }).catch(() => {
          this.$message.error('网络异常！')
        });
      }).catch(() => {
      });

    },
    handleSetDefault(index, row) {
      console.log(index, row);
      row.defaultFlag = true;
      this.update(row);
    },
    toDetails(activeName, item) {
      if (activeName === '4' || activeName === '5') {
        this.$router.push({path: '/order', query: {id: item.id}});
      } else if (activeName === '7') {
        this.$router.push({path: '/science-details', query: {id: item.scienceId}});
      }else {
        this.$router.push({path: '/details', query: {id: item.id}});
      }
    },
    handle(activeName, item, index) {
      console.log(activeName, item, index);
      this.$confirm('是否确认？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (activeName === '1') {
          this.$api.updateteaItem({
            id: item.id,
            teaStatus: 2
          }).then(res => {
            console.log(res);
            if (res.status_code === 1) {
              this.dataList[0].splice(index, 1);
              item.teaStatus = 2;
              this.dataList[1].unshift(item);
            } else {
              this.$message.error(res.msg)
            }
          });
        } else if (activeName === '2') {
          this.$api.updateteaItem({
            id: item.id,
            teaStatus: 0
          }).then(res => {
            console.log(res);
            if (res.status_code === 1) {
              this.dataList[1].splice(index, 1);
            } else {
              this.$message.error(res.msg)
            }
          });
        } else if (activeName === '3') {
          this.$api.deleteFavorite({
            id: item.favoriteId
          }).then(res => {
            console.log(res);
            if (res.status_code === 1) {
              this.$message({
                message: '已取消收藏！',
                type: 'success'
              });
              this.dataList[2].splice(index, 1);
            } else {
              this.$message.error(res.msg)
            }
          }).catch(e => {
          })
        }
      }).catch(() => {
      });

    },
    fileHandleSuccess(response, file, fileList) {
      console.log("file:", response, file, fileList);
      let imgUrl = response.data;
      this.imgFileList = [];
      this.$api.updateUserPublicInfo({
        avatar: imgUrl
      }).then(res => {
        console.log(res);
        this.userInfo.avatar = imgUrl;
        this.$globalData.userInfo.avatar = imgUrl;
      })
    },
    update(data) {
      this.$api.updateAddress(data).then(res => {
        if (res.status_code === 1) {
          this.getAddressData();
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
        } else {
          this.$message.error('系统异常，修改失败！')
        }
      }).catch(() => {
        this.$message.error('网络异常！')
      })
    },
    saveAddress() {
      if (this.addressInfo.id) {
        console.log('update:', this.addressInfo);
        this.update(this.addressInfo);
        this.addressInfo = {
          consigneeName: '',
          consigneePhone: '',
          provinceName: '',
          cityName: '',
          regionName: '',
          detailAddress: '',
          defaultFlag: false
        };
        this.selectedOptions = [];
      } else {
        if (this.addressData.length >= 5) {
          this.$message.error('已达到最大地址数量！')
        } else {
          console.log(this.addressInfo);
          this.$api.addAddress(this.addressInfo).then(res => {
            if (res.status_code === 1) {
              this.getAddressData();
              this.$message({
                message: '新增成功！',
                type: 'success'
              });
              this.selectedOptions = [];
              this.addressInfo = {
                consigneeName: '',
                consigneePhone: '',
                provinceName: '',
                cityName: '',
                regionName: '',
                detailAddress: '',
                defaultFlag: false
              };
            } else {
              this.$message.error('系统异常，新增失败！')
            }
          }).catch(e => {
            this.$message.error('网络异常！')
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.user-info-container {
  width: 100%;
  height: 200px;
  border-bottom: 15px solid #f6f6f6;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-info-details {
  display: flex;
  height: 140px;
  align-items: center;
  margin: 20px 40px;
}

.user-info-details-text {
  margin-left: 20px;
}

.user-info-details-text-nickname {
  font-size: 26px;
  font-weight: 600;
  margin: 10px 0;
}

.user-info-details-text-time {
  font-size: 14px;
  margin-bottom: 10px;
}

.user-info-splace {
  margin-right: 90px;
}

.tea-container {
  padding: 0 20px;
}

.tea-container-list {
  min-height: 55vh;
}

.tea-container-list-item {
  border-bottom: 1px solid #eeeeee;
  cursor: pointer;
}

.tea-container-list-item:last-child {
  border-bottom: none;
}

.tea-container-list-item-detile {
  height: 120px;
  display: flex;
  align-items: center;
}

.tea-container-list-item-text {
  margin-left: 10px;
  height: 120px;
  max-width: 800px;
}

.tea-container-list-title {
  font-weight: 600;
  font-size: 18px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.tea-container-list-tea-details {
  font-size: 14px;
  color: #555555;
  padding-top: 5px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.tea-container-list-tea-time {
  font-size: 13px;
  padding-top: 5px;
}

.tea-prive {
  font-size: 15px;
  padding-top: 5px;
  color: red;
}

.edit-tip {
  font-size: 14px;
  margin: 10px 5px;
}

.address-container {
  padding: 10px 20px;
}

.address-container-back {
  margin-bottom: 10px;
}

.address-container-add-title {
  color: #409EFF;
  padding: 10px;
  color: black;
  font-size: 28px;
}

.address-container-add-item {
  margin-bottom: 20px;
}

.demonstration {
  color: #666666;
  font-size: 14px;
  padding: 10px;
}

.address-container-add {
  padding: 0 200px;
}

.address-container-list {
  padding: 30px 100px;
}

.tea-item-foot {
  width: 800px;
  display: flex;
  justify-content: space-between;
}
</style>